import 'package:bili_caricature/base/base_grid_view.dart';
import 'package:bili_caricature/pages/bloc/widgets/car_toon_widget.dart';
import 'package:bili_caricature/pages/book_shelf/widget/crosswise_widget.dart';
import 'package:bili_caricature/pages/book_shelf/bili_book_shelf/event.dart';
import 'package:bili_caricature/pages/book_shelf/bili_book_shelf/state.dart';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../../base/base_stateful_page.dart';
import '../../../base/common_refresher.dart';
import '../../../base/loadiing_footer.dart';
import '../../../base/refresh_header.dart';
import '../../../routers/home_router.dart';
import '../../../routers/navigator_utils.dart';
import '../../../widgets/swiper_widget/swiper_widget.dart';
import 'bloc.dart';

class BlocStaggeredGridView extends BasePage {
  const BlocStaggeredGridView({super.key});

  @override
  BasePageState<BasePage> getState() {
    return _MessageModulePageState();
  }
}

class _MessageModulePageState extends BasePageState<BlocStaggeredGridView> {
  /// 请求分页
  int _pageNum = 1;

  /// 列表控制器
  final ScrollController scrollController = ScrollController();

  /// 刷新组建控制器
  final RefreshController refreshController = RefreshController(initialRefresh: false);

  /// 隐藏返回按钮
  @override
  Widget left() {
    return const SizedBox();
  }

  @override
  void initState() {
    super.initState();
    pageTitle = 'bloc-stagger';
    pageBgColor = const Color(0xFFF3F4F8);
    isBack = false;
    _getData();
    _getBanner();
  }

  /// 请求列表数据
  _getData() {
    String urlStr = '';
    if (_pageNum == 1) {
      urlStr = 'https://run.mocky.io/v3/8d98fef7-634f-4122-a837-8c9ee892365e';
    } else if (_pageNum == 2) {
      urlStr = 'https://run.mocky.io/v3/d415f483-bdbf-445d-ae12-703d1fd01e97';
    } else if (_pageNum == 3) {
      urlStr = 'https://run.mocky.io/v3/a9faaec6-d70f-4365-95b2-6abdd35a6e28';
    } else {
      urlStr = '';
    }
    BlocProvider.of<BlocStaggeredGridViewBloc>(context).add(
      GetListDataEvent(urlStr, _pageNum),
    );
  }

  /// 请求轮播图数据
  _getBanner() {
    BlocProvider.of<BlocStaggeredGridViewBloc>(context).add(
      GetBannerDataEvent('https://run.mocky.io/v3/8836074c-75e9-4384-8149-9faadbdedca0'),
    );
  }

  /// 上拉加载
  void _onLoading() {
    _pageNum++;
    _getData();
  }

  /// 下拉刷新
  void _onRefresh() {
    _pageNum = 1;
    _getData();
    _getBanner();
  }

  Widget mainWidget(StaggeredGridViewState state) {
    return CommonRefresher(
        enablePullDown: true,
        enablePullUp: true,
        refreshController: refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        listWidget: SingleChildScrollView(
          controller: scrollController,
          child: StaggeredGrid.count(
            crossAxisCount: 2,
            mainAxisSpacing: 10.h,
            crossAxisSpacing: 0,
            children: [
              ...state.dataList!.mapIndexed((index, tile) {
                return StaggeredGridTile.extent(
                  crossAxisCellCount: tile.crossAxisCount,
                  mainAxisExtent: index == 0 ? 200.h : (tile.crossAxisCount == 2 ? 180.h : 260.h),
                  child: index == 0
                      ? SwiperWidget(
                          imagesList: state.bannerList,
                          width: 1.sw,
                          height: 200.h,
                          type: 1,
                          onTap: (int index) {},
                          indexChangeTap: (int index) {},
                        )
                      : tile.crossAxisCount == 1
                          ? CarToonWidget(
                              index: index,
                              model: state.dataList![index],
                              isStaggeredGrid: true,
                              onTap: () {
                                NavigatorUtils.push(context, HomeRouter.biliMinePage,
                                    arguments: {"imageUrl": state.dataList![index].image});
                              },
                            )
                          : CrosswiseWidget(
                              model: state.dataList![index],
                              onTap: () {
                                NavigatorUtils.push(context, HomeRouter.novelDetailPage,
                                    arguments: {"imageUrl": state.dataList![index].image});
                              },
                            ),
                );
              }),
            ],
          ),
        ));
  }

  void _listener(BuildContext context, StaggeredGridViewState state) {
    refreshController.refreshCompleted();
    refreshController.loadComplete();
    if (state.isNoMoreDataState == true) {
      refreshController.loadNoData();
    }
  }

  @override
  Widget buildPage(BuildContext context) {
    return BlocConsumer<BlocStaggeredGridViewBloc, StaggeredGridViewState>(
      listener: _listener,
      builder: (context, state) {
        return resultWidget(state, (baseState, context) => mainWidget(state), refreshMethod: () {
          _pageNum = 1;
          _getData();
        });
      },
    );
  }
}
